package com.admin.bean;

import com.admin.model.AppUser;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class AutoSetAppUserInfo extends HandlerInterceptorAdapter {
    private final String SESSION_APPUSER = "SESSION_APPUSER";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String appUserJson = request.getHeader(SESSION_APPUSER);
        if (StringUtils.isNotEmpty(appUserJson)) {
            try {
                AppUserContext.setAppUser(JSONObject.parseObject(appUserJson, AppUser.class));
            } catch (Exception ignored) {

            }
        }

        return true;
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        AppUserContext.clearAppUser();
    }
}
